package com.czy.owner.ui.bottom;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.czy.owner.R;
import com.czy.owner.adapter.MessageFragmentAdapter;
import com.czy.owner.global.Constants;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.Subscribe;
import com.czy.owner.rxbus.ThreadMode;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.BaseFragment;
import com.czy.owner.ui.message.ContactsFragment;
import com.czy.owner.ui.message.ConversationFragment;
import com.czy.owner.ui.message.GroupFragment;
import com.czy.owner.ui.message.SearchMessageActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.widget.CustomViewPager;
import com.czy.owner.widget.PageTitleView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by wangyng on 2017/5/2 0002.
 * 消息
 */

public class MessageFragment extends BaseFragment  {
    private final String TAG = this.getClass().getSimpleName();

    @BindView(R.id.ll_message_search)
    LinearLayout llMessageSearch;
    @BindView(R.id.iv_message_tab_list)
    ImageView ivMessageTabList;
//    @BindView(R.id.iv_message_tab_group)
//    ImageView ivMessageTabGroup;
    @BindView(R.id.iv_message_tab_contacts)
    ImageView ivMessageTabContacts;
    @BindView(R.id.viewpager_message_container)
    CustomViewPager mViewPager;
    @BindView(R.id.tv_message_tab_list)
    TextView tvMessageTabList;
//    @BindView(R.id.tv_message_tab_group)
//    TextView tvMessageTabGroup;
    @BindView(R.id.tv_message_tab_contacts)
    TextView tvMessageTabContacts;
    @BindView(R.id.tv_message_tab_cursor)
    TextView tvMessageTabCursor;
//    @BindView(R.id.appbar_message)
//    AppBarLayout appBarMessage;
    @BindView(R.id.ll_message_hide)
    LinearLayout llMessageHide;
    @BindView(R.id.ll_tab_decoration)
    LinearLayout llDecoration;
    @BindView(R.id.tv_title)
    TextView tvTitle;

    private int llDecorationHeight = -1, llMessageHideHeight = -1;
    private List<Fragment> fragments;
    private ConversationFragment conversationFragment;
//    private GroupFragment groupFragment;
    private ContactsFragment contactsFragment;
    private MessageFragmentAdapter mMessageFragmentAdapter;

    private int cursorWidth, cursorOffset, cursorCurrent = 0;
    private TranslateAnimation mAnimation;
    private long decorationRefreshTime = 0 ;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_message;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        tvTitle.setText("消息");
        initTabs();
        llMessageSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent mIntent = new Intent(getContext(), SearchMessageActivity.class);
                startActivity(mIntent);
            }
        });
        //appBarMessage.addOnOffsetChangedListener(this);
        RxBus.getDefault().register(this);
    }

    @Override
    protected void updateViews() {

    }

    @Override
    public void onResume() {
        super.onResume();
        initCursor(cursorCurrent);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }
    public void initTabs() {
        fragments  = new ArrayList<>();
        conversationFragment =  new ConversationFragment();
        fragments.add(conversationFragment);
//        groupFragment = new GroupFragment();
//        fragments.add(groupFragment);
        contactsFragment = new ContactsFragment();
        fragments.add(contactsFragment);

        mMessageFragmentAdapter = new MessageFragmentAdapter(getChildFragmentManager(), fragments);
        mViewPager.setAdapter(mMessageFragmentAdapter);
        mViewPager.addOnPageChangeListener(new MessagePagerListener());
        ivMessageTabList.setOnClickListener(new tabsOnClickListener(0));
//        ivMessageTabGroup.setOnClickListener(new tabsOnClickListener(1));
        ivMessageTabContacts.setOnClickListener(new tabsOnClickListener(1));
        tvMessageTabList.setOnClickListener(new tabsOnClickListener(0));
//        tvMessageTabGroup.setOnClickListener(new tabsOnClickListener(1));
        tvMessageTabContacts.setOnClickListener(new tabsOnClickListener(1));
        mViewPager.setPagingEnabled(false);
        mViewPager.setOffscreenPageLimit(2);
        //tabLayout.setupWithViewPager(mViewPager);
    }

    private class tabsOnClickListener implements View.OnClickListener {
        private int index;

        public tabsOnClickListener(int position) {
            index = position;
        }

        @Override
        public void onClick(View v) {

            if (index == cursorCurrent) return;
            tvMessageTabList.getPaint().setFakeBoldText(false);
//            tvMessageTabGroup.getPaint().setFakeBoldText(false);
            tvMessageTabContacts.getPaint().setFakeBoldText(false);
            changCursor(cursorCurrent, index);
            cursorCurrent = index;
            mViewPager.setCurrentItem(cursorCurrent);
        }
    }



    private void initCursor(int cursorCurrent) {
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        // 获取分辨率宽度
        int screenW = dm.widthPixels- PhoneUtils.dip2px(getActivity(),18);
        // 获取TextView宽度
        int width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int height = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        tvMessageTabCursor.measure(width, height);
        cursorWidth = tvMessageTabCursor.getMeasuredWidth();
        cursorOffset = (screenW / 2 - cursorWidth) / 2;// 计算偏移量

        //初始化Cursor位置
        mAnimation = new TranslateAnimation(0, (cursorOffset * 2 + cursorWidth) * cursorCurrent + cursorOffset, 0, 0);
        mAnimation.setDuration(100);
        mAnimation.setFillAfter(true);
        tvMessageTabCursor.startAnimation(mAnimation);
    }

    private void changCursor(int fromCursor, int toCursor) {
        int fromXDelta = (cursorOffset * 2 + cursorWidth) * fromCursor + cursorOffset;
        int toXDelta = (cursorOffset * 2 + cursorWidth) * toCursor + cursorOffset;
        mAnimation = new TranslateAnimation(fromXDelta, toXDelta, 0, 0);
        mAnimation.setDuration(100);
        mAnimation.setFillAfter(true);
        tvMessageTabCursor.startAnimation(mAnimation);
    }

    public class MessagePagerListener implements ViewPager.OnPageChangeListener {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            changCursor(cursorCurrent, position);
            cursorCurrent = position;
            switch (position){
                case 0:
                    tvTitle.setText("消息");
                    break;
//                case 1:
//                    tvTitle.setText("群聊");
//                    break;
                case 1:
                    tvTitle.setText("通讯录");
                    break;

            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

//    @Override
//    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
//        if (llDecorationHeight == -1 || llMessageHideHeight == -1) {
//            llDecorationHeight = llDecoration.getHeight();
//            llMessageHideHeight = llMessageHide.getHeight();
//        } else if(System.currentTimeMillis() - decorationRefreshTime >= 50){
//            //MyLog.i(TAG, "onOffsetChanged:" + verticalOffset + "|" + llMessageHideHeight + "|" + llDecorationHeight);
//            ViewGroup.LayoutParams lp = llDecoration.getLayoutParams();
//            lp.height = (llMessageHideHeight - Math.abs(verticalOffset)) * llDecorationHeight / llMessageHideHeight;
//            llDecoration.setLayoutParams(lp);
//            decorationRefreshTime = System.currentTimeMillis();
//        }
//    }
    @Subscribe(code = Constants.RXBUS_CODE_REFRESH_MESSAGE, threadMode = ThreadMode.MAIN)
    public void refresh(String event){
        Log.i("King","RXBUS_CODE_REFRESH_MESSAGE:");
        if(conversationFragment!=null){
            conversationFragment.refresh();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unRegister(this);
    }
}
